package gui;

import java.util.ArrayList;
import java.util.List;

import framework.GraphicsWrapper;
import framework.Rectangle;

public class VerticalStackContainer implements Component {

	private boolean my_dirty = true;
	private int my_width;
	private int my_height;
	private Rectangle my_maxSize;
	private final List<Component> my_children;
	private int my_padding = 10;
	
	public VerticalStackContainer() {
		my_children = new ArrayList<Component>();
	}
	
	@Override
	public Rectangle getMinSize(GraphicsWrapper the_graphics) {
		int max_width = 0;
		int height = 0;
		for (Component child : my_children) {
			final Rectangle size = child.getMinSize(the_graphics);
			max_width = Math.max(max_width, (int)size.getWidth());
			height += (int)size.getHeight();
			height += my_padding;
		}
		height -= my_padding;
		return new Rectangle(max_width, height);
	}

	@Override
	public Rectangle getSize() {
		return new Rectangle(my_width, my_height);
	}

	@Override
	public void setSize(int the_width, int the_height) {
		my_width = the_width;
		my_height = the_height;
		
	}
	
	public void setMaxSize(final Rectangle the_size) {
		my_maxSize = the_size;
	}

	@Override
	public void setSize(Rectangle the_size) {
		my_width = (int)the_size.getWidth();
		my_height = (int)the_size.getHeight();
	}

	public void validate(GraphicsWrapper the_graphics) {
		for (Component child : my_children) {
			child.validate(the_graphics);
		}
		Rectangle size = getMinSize(the_graphics);
		for (Component child : my_children) {
			child.setSize((int)size.getWidth(), (int)child.getSize().getHeight());
		}
		my_width = (int)size.getWidth();
		my_height = (int)size.getHeight();
	}
	@Override
	public void render(GraphicsWrapper the_graphics) {
		if (my_dirty) {
			validate(the_graphics);
			my_dirty = false;
		}
		the_graphics.saveMatrix();
		the_graphics.translate((my_maxSize.getWidth() - my_width) / 2,
				(my_maxSize.getHeight() - my_height) / 2);
		for (Component child : my_children) {
			final Rectangle size = child.getSize();
			child.render(the_graphics);
			the_graphics.translate(0, size.getHeight() + my_padding);
		}
		the_graphics.restoreMatrix();
	}
	
	public void add(final Component the_component) {
		my_children.add(the_component);
		my_dirty = true;
		
	}

}
